package com.meida.module.arc.provider.service.impl;

import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.service.BaseAdminAccountService;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.oauth2.OpenOAuth2ClientProperties;
import com.meida.common.utils.ApiAssert;
import com.meida.common.utils.RedisUtils;
import com.meida.module.admin.provider.service.BaseUserService;
import com.meida.module.arc.client.constants.ArchiveConstants;
import com.meida.module.arc.provider.service.ArcAuthTokenService;
import com.meida.module.arc.provider.service.ArcCategoryService;
import com.meida.module.arc.provider.service.ArcSettingService;
import com.meida.module.system.provider.service.SysCompanyService;
import com.meida.module.virbox.provider.AuthTokenProvider;
import com.meida.module.virbox.provider.entity.AuthToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Map;

/**
 * <b>功能名：ArcAuthTokenServiceImpl</b><br>
 * <b>说明：</b><br>
 * <b>著作权：</b> Copyright (C) 2021 HUIFANEDU  CORPORATION<br>
 * <b>修改履历：
 *
 * @author 2022-02-14 jiabing
 */
@Service
public class ArcAuthTokenServiceImpl implements ArcAuthTokenService {
    @Autowired
    private AuthTokenProvider authTokenProvider;

    @Autowired
    private ArcSettingService arcSettingService;

    @Autowired
    private SysCompanyService sysCompanyService;

    @Autowired
    private BaseUserService baseUserService;

    @Autowired
    private ArcCategoryService arcCategoryService;

    @Autowired
    private BaseAdminAccountService baseAdminAccountService;
    @Autowired
    private OpenOAuth2ClientProperties clientProperties;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public AuthToken getLicense() {
        AuthToken token = authTokenProvider.getLicense();
        if(FlymeUtils.isNotEmpty(token)){
            Long authTime = token.getAuthTime();
            if(authTime!=0&&(System.currentTimeMillis() - authTime * 1000L > 0)){
                token = null;
            }
        }
        if(FlymeUtils.isEmpty(token)){
            ApiAssert.failure("License为空或已过期");
        }
        return token;
        //TODO SAAS版本这一块要重新设计  现在认为ArcSetting表只有一条数据
        // saas版本应该查询独赢用户的setting
//        Object idCode = null;
//        Object token = null;
//        Object obj = redisUtils.get(ArchiveConstants.REDIS_SETTING_KEY_PREFIX);
//        if (FlymeUtils.isNotEmpty(obj)) {
//            Map objMap = (Map) obj;
//            idCode = objMap.get("idCode");
//            token = objMap.get("token");
//        }
//        EntityMap setting = arcSettingService.findByTenant();
//        if (FlymeUtils.isNotEmpty(setting)) {
//            redisUtils.set(ArchiveConstants.REDIS_SETTING_KEY_PREFIX, setting, 60 * 30L);
//            idCode = setting.get("idCode");
//            token = setting.get("token");
//        }
//        AuthToken authToken = authTokenProvider.getAuthToken(idCode == null ? null : idCode.toString(), token == null ? null : token.toString());
//        if (FlymeUtils.isEmpty(authToken)) {
//            ApiAssert.failure("授权信息为空");
//        }
//        return authToken;
    }

    @Override
    public ResultBody checkTokenCode() {
        Object idCode = null;
        Object token = null;
        Object obj = redisUtils.get(ArchiveConstants.REDIS_SETTING_KEY_PREFIX);
        if (FlymeUtils.isNotEmpty(obj)) {
            Map objMap = (Map) obj;
            idCode = objMap.get("idCode");
            token = objMap.get("token");
        } else {
            EntityMap setting = arcSettingService.findByTenant();
            if (FlymeUtils.isNotEmpty(setting)) {
                redisUtils.set(ArchiveConstants.REDIS_SETTING_KEY_PREFIX, setting, 60 * 30L);
                idCode = setting.get("idCode");
                token = setting.get("token");
            }
        }
        if (FlymeUtils.isEmpty(token)) {
            return ResultBody.failed("该软件未授权激活");
        }
        String tokenCode = authTokenProvider.getTokenCode(idCode == null ? null : idCode.toString(), token == null ? null : token.toString(), false);
        if (FlymeUtils.isEmpty(tokenCode)) {
            return ResultBody.failed("该软件未授权激活");
        }
        AuthToken license = authTokenProvider.getLicense();
        if (FlymeUtils.isEmpty(license)) {
            return ResultBody.failed("License为空");
        }
        if (!tokenCode.equals(license.getCode())) {
            return ResultBody.failed("License与注册码不匹配");
        }
        return ResultBody.ok();
    }

    @Override
    public AuthToken readTokenFromTokenFile(File licenseFile) {
        return authTokenProvider.readTokenFromTokenFile(licenseFile);
    }

    @Override
    public Boolean checkDeptCount(Integer deptCount) {
        AuthToken token = getLicense();
        Integer authCount = token.getCategoryCount();
        if (FlymeUtils.isEmpty(authCount)) {
            ApiAssert.failure("授权部门数量为null");
        }
        if (FlymeUtils.isNotEmpty(deptCount) && authCount != 0 && authCount <= deptCount) {
            ApiAssert.failure("您的授部门构数量为" + authCount);
        }
        return true;
    }

    @Override
    public Boolean checkUserCount(Integer userCount) {
        AuthToken token = getLicense();
        Integer authCount = FlymeUtils.getInteger(token.getUserCount(), 0);
        //为0代表不限制
        if (authCount.equals(0)) {
            return true;
        }
        if (userCount.equals(authCount)) {
            return false;
        }
        return true;
    }

    @Override
    public void checkCategoryCount() {
        Long count = arcCategoryService.count();
        AuthToken token = getLicense();
        Integer authCount = token.getCategoryCount();
        if (FlymeUtils.isEmpty(authCount)) {
            ApiAssert.failure("授权门类数量为null");
        }
        if (FlymeUtils.isNotEmpty(count) && authCount != 0 && authCount <= count) {
            ApiAssert.failure("您的授权门类数量为" + authCount);
        }
    }

    @Override
    public Boolean checkCompanyCount(Integer companyCount) {

        AuthToken token = getLicense();
        Integer authQzCount = token.getQzCount();
        if (FlymeUtils.isEmpty(authQzCount)) {
            ApiAssert.failure("授权全宗数量为null");
        }
        if (FlymeUtils.isNotEmpty(companyCount) && authQzCount != 0 && authQzCount <= companyCount) {
            ApiAssert.failure("您的授权全宗数量为" + authQzCount);
        }
        return true;
    }

    @Override
    public Boolean checkOnlineCount(Integer onlineCount) {
        if(onlineCount==0){
            //0为 不限制
            return true;
        }
        Long userCount = FlymeUtils.getLong(baseUserService.countOnLine(),0L);
        System.out.println("在线用户数量###############################" + userCount);
        if (onlineCount <= userCount.intValue()) {
            return false;
        }
        return true;
    }

}
